<script setup>
import {ref, onMounted, watch, computed, reactive} from 'vue'
import {
  ElTable,
  ElTableColumn,
  ElInput,
  ElDatePicker,
  ElSelect,
  ElOption,
  ElButton,
  ElDialog,
  ElPagination  // 新增导入
} from 'element-plus'
import axios from 'axios'


// 分页配置
const paginationConfig = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 重置分页状态
const resetPagination = () => {
  paginationConfig.currentPage = 2
  paginationConfig.pageSize = 10
}

// 分页变化处理
const handlePageChange = (newPage) => {
  paginationConfig.currentPage = newPage
  fetchLogs()
}

const handleSizeChange = (val) =>{
  paginationConfig.pageSize=val
  fetchLogs()
}




// 日志数据
const logData = ref([])
// 原始日志数据，用于筛选
const originalLogData = ref([])
// 查询条件，需根据实际情况调整筛选字段名
const searchForm = ref({
  username: '', // 对应后端 username
  action: '', // 对应后端 action
  role: '', // 对应后端 role
  recordType: '', // 对应后端 recordType
  actionTimeRange: [] // 操作时间筛选条件
})


// 控制弹窗显示状态
const dialogVisible = ref(false)
// 存储当前查看的日志信息
const currentLog = ref({})
// 存储获取的健康记录信息
const healthRecord = ref({})

// 用户身份选项
const userRoleOptions = [
  { label: '用户', value: '用户' },
  { label: '医护人员', value: '医护人员' },
  { label: '健康管理师', value: '健康管理师' },
  { label: '管理员', value: '管理员' }
]

// 操作类型选项（复用已有逻辑，可按需调整）
const actionTypeOptions = [
  { label: '查询', value: '查询' },
  { label: '修改', value: '修改' },
  { label: '删除', value: '删除' },
  { label: '增加', value: '增加' }
]

// 访问模块选项
const moduleOptions = [
  { label: '过敏史', value: '过敏史' },
  { label: '家族病史', value: '家族病史' },
  { label: '体检报告', value: '体检报告' },
  { label: '健康指标', value: '健康指标' },
  { label: '用药记录', value: '用药记录' },
  { label: '既往病史', value: '既往病史' }
]

// 时间格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
}

// 获取日志数据
const fetchLogs = async () => {
  try {
    const response = await axios.get('http://localhost:8080/log', {
      params: {
        ...searchForm.value,
        pageNum: paginationConfig.currentPage,
        pageSize: paginationConfig.pageSize

      }
    })
    console.log(response)
    originalLogData.value =response.data ;
  } catch (error) {
    console.error('获取日志数据失败:', error)
    originalLogData.value = []
    paginationConfig.total = 0
  }
  handleSearch()
  console.log(paginationConfig.total)
}

// 执行查询，需根据新属性名调整筛选逻辑
const handleSearch = () => {
  const startIndex = (paginationConfig.currentPage - 1) * paginationConfig.pageSize;
  const endIndex = startIndex +paginationConfig.pageSize;
  const abc = ref([])
  abc.value = originalLogData.value.filter(log => {
    const matchUser = !searchForm.value.username || log.username.includes(searchForm.value.username)
    const matchRole = !searchForm.value.role || log.role === searchForm.value.role
    const matchAction = !searchForm.value.action || log.action === searchForm.value.action
    const matchRecordType = !searchForm.value.recordType || log.recordType === searchForm.value.recordType
    let matchActionTime = true
    if (searchForm.value.actionTimeRange && searchForm.value.actionTimeRange.length === 2) {
      const [startTime, endTime] = searchForm.value.actionTimeRange
      const actionTime = new Date(log.logTime)
      matchActionTime = actionTime >= new Date(startTime) && actionTime <= new Date(endTime)
    }

    return matchUser && matchRole && matchAction && matchRecordType && matchActionTime
  })
  paginationConfig.total=abc.value.length;
logData.value=abc.value.slice(startIndex,endIndex)
}


// 解析 detail 数据的函数，根据 recordType 调用不同的解析逻辑
const parseHealthRecordDetail = (record) => {
  if (!record.detail) {
    console.log('record.detail 为空或非字符串:', record);
    return {};
  }
  console.log('当前解析的 recordType:', record.recordType, 'detail:', record.detail);
  const parts = record.detail.split('|');
  const recordType = record.recordType ? record.recordType.trim() : '';
  switch (recordType.toLowerCase()) {
    case '过敏史':
      return {
        allergen: parts[0] || '',
        forbiddenDrugs: parts[1] || '',
        treatmentDrugs: parts[2] || '',
        avoidanceMethod: parts[3] || '',
        remarks: parts[4] || ''
      };
    case '家族病史':
      return {
        patientName: parts[0] || '',
        diseaseName: parts[1] || '',
        relationship: parts[2] || '',
        onsetFrequency: parts[3] || '',
        remarks: parts[4] || ''
      };
    case '健康指标':
      try {
        return {
          height: parts[0] ? parseFloat(parts[0]) || 0 : 0,
          weight: parts[1] ? parseFloat(parts[1]) || 0 : 0,
          bmi: parts[2] ? parseFloat(parts[2]) || 0 : 0,
          bloodPressure: parts[3] || '',
          bloodSugar: parts[4] || '',
          heartRate: parts[5] || '',
          remarks: parts[6] || ''
        };
      } catch (e) {
        console.log('解析健康指标失败:', e, 'parts:', parts);
        return {
          height: 0,
          weight: 0,
          bmi: 0,
          bloodPressure: '',
          bloodSugar: '',
          heartRate: '',
          remarks: ''
        };
      }
    case '体检报告':
      return {
        abnormalIndicators: parts[0] || '',
        condition: parts[1] || '',
        medicalAdvice: parts[2] || '',
        examinationInstitution: parts[3] || '',
        examinationDoctor: parts[4] || '',
        remarks: parts[5] || ''
      };
    case '用药记录':
      return {
        medicationReason: parts[0] || '',
        medicationName: parts[1] || '',
        usageAndDosage: parts[2] || '',
        medicationResult: parts[3] || '',
        drugSideEffects: parts[4] || '',
        remarks: parts[5] || ''
      };
    case '既往病史':
      return {
        diseaseName: parts[0] || '',
        symptoms: parts[1] || '',
        cause: parts[2] || '',
        treatmentProcess: parts[3] || '',
        hasSequel: parts[4] || '',
        remarks: parts[5] || ''
      };
    default:
      console.log('未知的 recordType:', recordType);
      return {detail: record.detail};
  }
}

// 查看日志详情并获取健康记录函数，打开弹窗并存储当前日志信息
const viewLogDetail = async (log) => {
  currentLog.value = log
  try {
    const response = await axios.get(`http://localhost:8080/log/getHealthRecord/${log.recordId}`);
    console.log('获取健康记录成功:', response.data);
    healthRecord.value = response.data;
    // 解析 detail 数据
    healthRecord.value.parsedDetail = parseHealthRecordDetail(response.data);
  } catch (error) {
    console.error('获取健康记录失败:', error);
    healthRecord.value = {};
  }
  dialogVisible.value = true
}
// 暴露分页方法
defineExpose({
  resetPagination
})
onMounted(() => {
  fetchLogs()
})
// 监听总条数变化（当数据更新时自动修正页码）
watch(
    () => paginationConfig.total,
    (newVal) => {
      if (newVal <= (paginationConfig.currentPage - 1) * paginationConfig.pageSize && newVal > 0) {
        paginationConfig.currentPage = Math.ceil(newVal / paginationConfig.pageSize)
      }
    }
)
// 删除日志函数
const deleteLog = async (logId) => {
  try {
    await axios.delete(`http://localhost:8080/log/delete/${logId}`);
    console.log('日志删除成功');
    fetchLogs(); // 删除成功后重新获取日志数据
  } catch (error) {
    console.error('删除日志失败:', error);
  }
}
</script>

<template>
  <div class="log-container">
    <!-- 添加返回按钮 -->
    <RouterLink to="/user-manage" class="back-button">返回用户管理</RouterLink>

    <div class="search-form">
      <ElInput v-model="searchForm.username" placeholder="请输入用户名"/>
      <ElSelect v-model="searchForm.action" placeholder="请选择操作类型" @change="handleSearch">
        <ElOption label="全部" value=""/>
        <ElOption v-for="item in actionTypeOptions" :key="item.value" :label="item.label" :value="item.value"/>
      </ElSelect>
      <!-- 新增用户角色下拉框 -->
      <ElSelect v-model="searchForm.role" placeholder="请选择用户角色" @change="handleSearch">
        <ElOption label="全部" value=""/>
        <ElOption v-for="item in userRoleOptions" :key="item.value" :label="item.label" :value="item.value"/>
      </ElSelect>
      <!-- 新增记录类型下拉框 -->
      <ElSelect v-model="searchForm.recordType" placeholder="请选择记录类型" @change="handleSearch">
        <ElOption label="全部" value=""/>
        <ElOption v-for="item in moduleOptions" :key="item.value" :label="item.label" :value="item.value"/>
      </ElSelect>
      <ElDatePicker
          v-model="searchForm.actionTimeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始操作时间"
          end-placeholder="结束操作时间"
      />
      <ElButton type="primary" @click="handleSearch">查询</ElButton>
    </div>

    <ElTable :data="logData" style="width: 100%">
      <ElTableColumn prop="logId" label="日志编号"/>
      <ElTableColumn prop="id" label="用户 ID"/>
      <ElTableColumn prop="role" label="用户角色"/>
      <ElTableColumn prop="username" label="用户名"/>
      <ElTableColumn prop="loginTime" label="登录时间">
        <template #default="{ row }">
          {{ formatDate(row.loginTime) }}
        </template>
      </ElTableColumn>
      <ElTableColumn prop="ip" label="IP 地址"/>
      <ElTableColumn prop="recordType" label="记录类型"/>
      <ElTableColumn prop="action" label="操作内容"/>
      <ElTableColumn prop="logTime" label="操作时间">
        <template #default="{ row }">
          {{ formatDate(row.logTime) }}
        </template>
      </ElTableColumn>
      <ElTableColumn prop="recordId" label="修改档案编号"/>
      <ElTableColumn label="操作">
        <template #default="{ row }">
          <ElButton type="text" @click="() => viewLogDetail(row)">查看</ElButton>
          <ElButton type="text" @click="() => deleteLog(row.logId)">删除</ElButton>
        </template>
      </ElTableColumn>
    </ElTable>

<!--    &lt;!&ndash; 分页组件 &ndash;&gt;-->
<!--    <div class="pagination-container">-->
<!--      <el-pagination-->
<!--          :current-page="paginationConfig.currentPage"-->
<!--          :page-size="paginationConfig.pageSize"-->
<!--          :page-sizes="paginationConfig.pageSizes"-->
<!--          :total="paginationConfig.total"-->
<!--          layout="total, sizes, prev, pager, next, jumper"-->
<!--          @size-change="handleSizeChange"-->
<!--          @current-change="handlePageChange"-->
<!--      />-->
<!--    </div>-->
    <!-- 分页组件 -->
    <div class="pagination-controls">
      <el-pagination
          :current-page="paginationConfig.currentPage"
          :page-size="paginationConfig.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"

          :total="paginationConfig.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>

    <ElDialog v-model="dialogVisible" title="日志详情" width="50%" class="log-detail-dialog">
      <!-- 展示健康记录信息 -->
      <div class="log-info">
        <p><span class="label">日志编号:</span> {{ currentLog.logid }}</p>
        <p><span class="label">用户 ID:</span> {{ currentLog.id }}</p>
        <p><span class="label">用户角色:</span> {{ currentLog.role }}</p>
        <p><span class="label">用户名:</span> {{ currentLog.username }}</p>
        <p><span class="label">登录时间:</span> {{ formatDate(currentLog.loginTime) }}</p>
        <p><span class="label">IP 地址:</span> {{ currentLog.ip }}</p>
        <p><span class="label">操作内容:</span> {{ currentLog.action }}</p>
        <p><span class="label">操作时间:</span> {{ formatDate(currentLog.logTime) }}</p>
        <p><span class="label">修改档案编号:</span> {{ currentLog.recordId }}</p>
      </div>
      <!-- 当操作类型为查询、增加或删除时，展示健康记录详细信息 -->
      <div v-if="currentLog.action === '查询'||currentLog.action === '修改'|| currentLog.action === '增加'|| currentLog.action === '删除'"
           class="health-record">
        <h3>健康记录信息</h3>
        <p><span class="label">记录日期:</span> {{ healthRecord.recordDate }}</p>
        <p><span class="label">记录 ID:</span> {{ healthRecord.recordId }}</p>
        <p><span class="label">记录类型:</span> {{ healthRecord.recordType }}</p>
        <div v-if="healthRecord.recordType?.toLowerCase() === '过敏史'" class="record-content">
          <p><span class="label">过敏原:</span> {{ healthRecord.parsedDetail.allergen }}</p>
          <p><span class="label">禁用药物:</span> {{ healthRecord.parsedDetail.forbiddenDrugs }}</p>
          <p><span class="label">治疗药物:</span> {{ healthRecord.parsedDetail.treatmentDrugs }}</p>
          <p><span class="label">避免方式:</span> {{ healthRecord.parsedDetail.avoidanceMethod }}</p>
          <p><span class="label">备注:</span> {{ healthRecord.parsedDetail.remarks }}</p>
        </div>
        <div v-else-if="healthRecord.recordType?.toLowerCase() === '家族病史'">
          <p>病人姓名: {{ healthRecord.parsedDetail.patientName }}</p>
          <p>疾病名称: {{ healthRecord.parsedDetail.diseaseName }}</p>
          <p>亲属关系: {{ healthRecord.parsedDetail.relationship }}</p>
          <p>发病频次: {{ healthRecord.parsedDetail.onsetFrequency }}</p>
          <p>备注: {{ healthRecord.parsedDetail.remarks }}</p>
        </div>
        <div v-else-if="healthRecord.recordType?.toLowerCase() === '健康指标'">
          <p>身高: {{ healthRecord.parsedDetail.height }} cm</p>
          <p>体重: {{ healthRecord.parsedDetail.weight }} kg</p>
          <p>BMI 指数: {{ healthRecord.parsedDetail.bmi }}</p>
          <p>血压: {{ healthRecord.parsedDetail.bloodPressure }}</p>
          <p>血糖: {{ healthRecord.parsedDetail.bloodSugar }}</p>
          <p>心率: {{ healthRecord.parsedDetail.heartRate }}</p>
          <p>备注: {{ healthRecord.parsedDetail.remarks }}</p>
        </div>
        <div v-else-if="healthRecord.recordType?.toLowerCase() === '体检报告'">
          <p>异常指标: {{ healthRecord.parsedDetail.abnormalIndicators }}</p>
          <p>病情: {{ healthRecord.parsedDetail.condition }}</p>
          <p>医嘱: {{ healthRecord.parsedDetail.medicalAdvice }}</p>
          <p>体检机构: {{ healthRecord.parsedDetail.examinationInstitution }}</p>
          <p>体检医生: {{ healthRecord.parsedDetail.examinationDoctor }}</p>
          <p>备注: {{ healthRecord.parsedDetail.remarks }}</p>
        </div>
        <div v-else-if="healthRecord.recordType?.toLowerCase() === '用药记录'">
          <p>用药原因: {{ healthRecord.parsedDetail.medicationReason }}</p>
          <p>药品名称: {{ healthRecord.parsedDetail.medicationName }}</p>
          <p>用法用量: {{ healthRecord.parsedDetail.usageAndDosage }}</p>
          <p>用药结果: {{ healthRecord.parsedDetail.medicationResult }}</p>
          <p>药物副作用: {{ healthRecord.parsedDetail.drugSideEffects }}</p>
          <p>备注: {{ healthRecord.parsedDetail.remarks }}</p>
        </div>
        <div v-else-if="healthRecord.recordType?.toLowerCase() === '既往病史'">
          <p>疾病名称: {{ healthRecord.parsedDetail.diseaseName }}</p>
          <p>症状: {{ healthRecord.parsedDetail.symptoms }}</p>
          <p>病因: {{ healthRecord.parsedDetail.cause }}</p>
          <p>治疗过程: {{ healthRecord.parsedDetail.treatmentProcess }}</p>
          <p>是否有后遗症: {{ healthRecord.parsedDetail.hasSequel }}</p>
          <p>备注: {{ healthRecord.parsedDetail.remarks }}</p>
        </div>
        <div v-else>
          <p>详情: {{ healthRecord.detail }}</p>
        </div>
      </div>
      <!-- 当操作类型不为查询、增加或删除时，展示原始健康记录 -->
      <pre v-else class="raw-record">{{ healthRecord }}</pre>
    </ElDialog>
  </div>
</template>

<style scoped>
.log-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  overflow-x: auto;
}

.search-form > * {
  margin-right: 10px;
  width: 200px;
}

.log-detail-dialog {
  .el-dialog__body {
    padding: 20px;
  }
}

.log-info {
  margin-bottom: 20px;
}

.label {
  font-weight: bold;
  color: #606266;
  margin-right: 8px;
}

.health-record {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.health-record h3 {
  color: #303133;
  margin-top: 0;
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.record-content {
  padding-left: 15px;
}

.raw-record {
  padding: 15px;
  background-color: #f0f2f5;
  border-radius: 4px;
  overflow-x: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 添加返回按钮样式 */
.back-button {
  display: inline-block;
  padding: 12px 20px;
  margin-bottom: 20px;
  background-color: #667eea;
  color: white;
  text-decoration: none;
  border-radius: 6px;
  font-size: 16px;
  transition: background-color 0.3s;
}

.back-button:hover {
  background-color: #5a67d8;
}
</style>